package cn.pzaily.fealetter.netty;

import cn.pzaily.crab.tools.core.utils.ObjectUtils;
import cn.pzaily.crab.tools.core.utils.StringUtils;
import cn.pzaily.crab.tools.http.result.ResponseResult;
import cn.pzaily.fealetter.dto.ParamsDTO;
import cn.pzaily.fealetter.service.impl.SendServiceImpl;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.net.InetSocketAddress;

/**
 * @PackageName: cn.pzaily.fealetter.netty
 * @Description:
 * @Author: Pang
 * @Date: 2021-11-22 9:44
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    private ApplicationContext applicationContext;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        // TODO TCP短信接收服务，接收应用系统的报文并解析，调用Service将消息保存到消息缓冲区
        ResponseResult result = ResponseResult.okResult();
        try {
            ParamsDTO paramsDTO = parseMessage(s);
            if (null == paramsDTO) {
                return;
            }
            applicationContext.getBean(SendServiceImpl.class).send(paramsDTO);
        } catch (BeansException e) {
            result = ResponseResult.errorResult(e.getMessage());
        }
        channelHandlerContext.writeAndFlush(result + "\n");

    }

    private ParamsDTO parseMessage(String message) {
        if (StringUtils.isEmpty(message)) {
            return null;
        }
        message = message.trim();

        ParamsDTO paramsDTO = JSON.parseObject(message, ParamsDTO.class);
        if (checkoutParamsDTOProperties(paramsDTO)) {
            return null;
        }

        return paramsDTO;
    }



    private boolean checkoutParamsDTOProperties(ParamsDTO paramsDTO) {
        return (null == paramsDTO
                || StringUtils.isEmpty(paramsDTO.getMobile())
                || StringUtils.isEmpty(paramsDTO.getSignature())
                || StringUtils.isEmpty(paramsDTO.getTemplate())
                || ObjectUtils.isNull(paramsDTO.getParams())) ? true : false;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inetSocketAddress.getAddress().getHostAddress();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
